﻿/*******************************************************************************
 * Copyright © 2016 NFine.Framework 版权所有
 * Author: NFine
 * Description: NFine快速开发平台
 * Website：http://www.nfine.cn
*********************************************************************************/

using System;
using NFine.Code;
using NFine.Data;
using NFine.Domain._03_Entity.Biz;
using NFine.Domain.Entity.SystemManage;
using NFine.Domain.IRepository.SystemManage;
using NFine.Repository.SystemManage;

namespace NFine.Repository.SystemManage
{
    public class UserRepository : RepositoryBase<UserEntity>, IUserRepository
    {
        public void DeleteForm(string keyValue)
        {
            using (var db = new RepositoryBase().BeginTrans())
            {
                db.Delete<UserEntity>(t => t.F_Id == keyValue);
                db.Delete<UserLogOnEntity>(t => t.F_UserId == keyValue);
                db.Delete<UserDetailEntity>(t => t.F_UserId == keyValue);
                db.Delete<UserPropertyEntity>(t => t.F_UserId == keyValue);
                db.Delete<UserGiveEntity>(t => t.F_GiveUserId == keyValue);
                db.Delete<UserBankEntity>(t => t.F_UserId == keyValue);
                db.Delete<UserWithdrawalsEntity>(t => t.F_UserId == keyValue);
                db.Delete<BalanceRecordEntity>(t => t.F_Id == keyValue);
                db.Delete<MemberBonusEntity>(t => t.F_MemberId == keyValue);
                db.Delete<ZhongZhuanPinJianEntity>(t => t.F_UserID == keyValue);
                var list = db.FindList<NFine.Domain.Entity.Biz.UserOrderEntity>("SELECT * FROM biz_user_order WHERE F_MemberId = '"+keyValue+"'");
                foreach (var order in list)
                {
                    db.Delete<NFine.Domain.Entity.Biz.OrderItemEntity>(t => t.F_OrderCode == order.F_OrderCode);
                    db.Delete<NFine.Domain.Entity.Biz.OrderActionEntity>(t => t.F_OrderCode == order.F_OrderCode);
                    db.Delete<NFine.Domain.Entity.Biz.UserOrderEntity>(order);
                }
                db.Commit();
            }
        }

        public int GetAllMemberCount(string roleId,string tid)
        {
            return GetSingleToInt(string.Format("SELECT COUNT(*) as result FROM  sys_user where (F_RoleId = '{0}' or F_RoleId = '{1}') and F_DutyId='1'", roleId,tid));
        }

        public int GetAllMemberCurMonth(string roleId, string tid)
        {
            return GetSingleToInt(string.Format("SELECT COUNT(*) as result FROM  sys_user where (F_RoleId = '{0}' or F_RoleId = '{1}') and F_DutyId='1' and DATE_FORMAT(F_jihuoTime, '%Y%m') = DATE_FORMAT(CURDATE( ) , '%Y%m')", roleId,tid));
        }

        public int GetMemberCountByDepartmentIdAndUserId(string departmentId, string userId = "")
        {
            string sql = "";
            if (string.IsNullOrEmpty(userId))
            {
                sql = string.Format("SELECT Count(*) FROM sys_user WHERE F_DepartmentId = '{0}'", departmentId);
            }
            else
            {
                sql = string.Format("SELECT Count(*) FROM sys_user WHERE F_DepartmentId = '{0}' AND F_Id != '{1}'", departmentId, userId);
            }
            return GetSingleToInt(sql);
        }

        public int GetMemberCountByDate(DateTime date, string roleId, string tid)
        {
            string sql = string.Format(
                "SELECT COUNT(*) as result  from sys_user WHERE date_format(F_CreatorTime, '%Y-%m-%d') = date_format('{0}', '%Y-%m-%d') and (F_RoleId = '{1}' or F_RoleId = '{2}') and F_DutyId='1'",
                date, roleId,tid);
            return GetSingleToInt(sql);
        }

        public int SubmitForm(UserEntity userEntity, UserLogOnEntity userLogOnEntity, string keyValue, UserDetailEntity userDetail=null)
        {
            using (var db = new RepositoryBase().BeginTrans())
            {
                if (!string.IsNullOrEmpty(keyValue))
                {
                    db.Update(userEntity);
                }
                else
                {
                    userLogOnEntity.F_Id = userEntity.F_Id;
                    userLogOnEntity.F_UserId = userEntity.F_Id;
                    userLogOnEntity.F_UserSecretkey = Md5.md5(Common.CreateNo(), 16).ToLower();
                    userLogOnEntity.F_UserPassword = Md5.md5(DESEncrypt.Encrypt(Md5.md5(userLogOnEntity.F_UserPassword, 32).ToLower(), userLogOnEntity.F_UserSecretkey).ToLower(), 32).ToLower();
                    db.Insert(userEntity);
                    db.Insert(userLogOnEntity);

                    if (userDetail != null)
                    {
                        userDetail.F_UserId = userEntity.F_Id;
                        userDetail.F_UserName = userEntity.F_RealName;
                        db.Insert(userDetail);

                        UserPropertyEntity userProperty = new UserPropertyEntity();
                        userProperty.F_UserId = userEntity.F_Id;
                        userProperty.F_Id = userEntity.F_Id;
                        userProperty.F_Property = 0;
                        db.Insert(userProperty);
                    }
                }
              return   db.Commit();
            }
        }

        public bool UpdateUser(UserDetailEntity ud, UserEntity u)
        {
            using (var db = new RepositoryBase().BeginTrans())
            {
                db.Update(ud);
                db.Update(u);
                return db.Commit()>0;
            }
        }


        /// <summary>
        /// 删除30天前的未注册的用户，自动完成
        /// </summary>
        /// <returns></returns>
        public int userDelete_auto()
        {
           var res= dbcontext.Database.ExecuteSqlCommand(string.Format("DELETE FROM sys_user WHERE F_Id IN (SELECT F_UserId FROM biz_user_detail WHERE F_UserLevel=0) AND DATE_SUB(NOW(), INTERVAL 1 MONTH)>F_CreatorTime"));
            if (res > 0) {
                dbcontext.Database.ExecuteSqlCommand(string.Format("DELETE FROM biz_user_detail WHERE F_UserId NOT IN(SELECT F_Id FROM sys_user)"));
                dbcontext.Database.ExecuteSqlCommand(string.Format("DELETE FROM sys_userlogon WHERE F_UserId NOT IN(SELECT F_Id FROM sys_user)"));
            }
            return res;
        }
    }
}
